﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Compilation;
using Web7.Core.Configuration;
using Web7.Extensions;
using Web7.Ioc;

namespace Web7.Core.Apps
{
    public class AppManagement : IDependencyDemandBuilder
    {
        private readonly List<IApp> _apps=new List<IApp>();

        public AppManagement()
        {
            SetupApps();
        }

        private void SetupApps()
        {
            Web7ConfigurationSection configuration = (Web7ConfigurationSection)ConfigurationManager.GetSection("web7");
            foreach (Web7AppConfigurationElement app in configuration.Apps)
            {
                if (app != null && app.Enabled)
                {
                    Type type = Type.GetType(app.Type);
                    if (type == null && BuildManager.CodeAssemblies != null)
                    {
                        foreach (var assembly in BuildManager.CodeAssemblies)
                        {
                            type = ((Assembly)assembly).GetExportedTypes().FirstOrDefault(t => t.FullName == app.Type);

                            if (type != null) break;
                        }
                    }
                    if (type == null)
                    {
                        throw new TypeLoadException("Could not load type '{0}'.".FormatWith(app.Type));
                    }

                    var appInstance = Activator.CreateInstance(type) as IApp;

                    appInstance.Settings = app.Settings.ToNameValueCollection();

                    _apps.Add(appInstance);
                }
            }
        }

        public void Build(IWeb7ContainerBuilder containerBuilder, IBuilderContext context)
        {
            foreach (IApp app in _apps)
            {
                containerBuilder.AddDemandsFromAssemblyOf(app.GetType());

                app.Initialize();
                app.RegisterRoutes();
            }
        }
    }
}
